package cn.alusiaor.eurekaclientarticleservice.config;

import cn.alusiaor.eurekaclientarticleservice.filters.LogFilter;
import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: zhuzhiping
 * @Description:
 * @Date: 2020/12/28 11:18
 */

@Configuration
@Slf4j
public class FeignInterceptorConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {

        RequestInterceptor requestInterceptor = template -> {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes servletRequestAttributes=(ServletRequestAttributes)requestAttributes;
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String traceId = MDC.get(LogFilter.KEY_LOG);
            log.info("日志requestId={}",traceId);
            template.header(LogFilter.KEY_LOG, traceId);
            template.header("token", request.getHeader("token"));
        };
        return requestInterceptor;
    }
}
